/*
 * JBeagle - a Java toolkit for genetic algorithms.
 * 
 * Copyright (c) 2010 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jbeagle.core.select;

import java.util.Collections;

import jbeagle.core.Individual;
import jbeagle.core.Population;

public class ElitistSelector implements Selector {

	protected Selector selector;
	protected int numToRetain;
	
	public ElitistSelector( Selector s, int numToRetain ) {
		selector = s;
		this.numToRetain = numToRetain;
	}
	
	public <I extends Individual<G>, G> Population<I, G> apply( Population<I, G> pop ) {
		Individual[] elites = new Individual[numToRetain];
		if ( numToRetain > 1 ) {
			Collections.sort(pop);
			for ( int i = 0; i < numToRetain; i++ )
				elites[i] = pop.get(i);
		} else
			elites[0] = pop.getFittest();
		
		Population<I, G> nextPop = selector.apply(pop);
		
		int pos;
		for ( int i = 0; i < numToRetain; i++ ) {
			pos = (int) Math.round(Math.random() * (pop.size()-1));
			nextPop.set(pos, (I) elites[i]); 
		}
		return nextPop;
	}
}
